import React, { useContext, useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Link } from "react-router-dom";
import { AppState } from "../App";
import Pagination from "./Pagination";
import {
  FaUser,
  FaCheck,
  FaDonate,
  FaWallet,
  FaMoneyBill,
} from "react-icons/fa";
import "../css/profile.css";
import "../css/loader.css";
import axios from "axios";

export default function Profile({ address }) {
  const App = useContext(AppState);
  const navigate = useNavigate();
  const [totalDonation, setTotalDonation] = useState(0);
  const [accountBalance, setAccountBalance] = useState(0);
  const [votedRequestData, setVotedRequestData] = useState([]);
  const [donationDetails, setDonationDetails] = useState([]);
  const [loading, setLoading] = useState(true);
  const [currentView, setCurrentView] = useState("personal-info");
  const [transactions, setTransactions] = useState([]);
  const [personalRequests, setPersonalRequests] = useState([]);
  //投票、捐款、hash记录和个人筹款记录分页
  const [currentPage, setCurrentPage] = useState({
    votedRecords: 1,
    donationRecords: 1,
    hashsRecords: 1,
    personalRequests: 1,
  });
  const itemsPerPage = 2; //每页显示的数量
  const handlePageChange = (view, page) => {
    setCurrentPage((prevState) => ({ ...prevState, [view]: page }));
  };

  //计算总页数
  const totalPages = {
    votedRecords: Math.ceil(votedRequestData.length / itemsPerPage),
    donationRecords: Math.ceil(donationDetails.length / itemsPerPage),
    hashsRecords: Math.ceil(transactions.length / itemsPerPage),
    personalRequests: Math.ceil(personalRequests.length / itemsPerPage),
  };

  useEffect(() => {
    const fetchUserData = async () => {
      setLoading(true);
      try {
        const totalDonationAmount =
          await App.Foundationcontract.getContributorMoney(address);
        const accountBalance =
          await App.Foundationcontract.getContributorBalance(address);
        const requestIds =
          await App.Foundationcontract.getContributorRequestIds(address);
        const requestAddresses =
          await App.Foundationcontract.getContributorAddresses(address);
        const descriptions =
          await App.Foundationcontract.getContributorDescriptions(address);
        const targetAmounts =
          await App.Foundationcontract.getContributorTargetAmounts(address);
        const completedStatus =
          await App.Foundationcontract.getContributorCompletedStatus(address);
        const photos = await App.Foundationcontract.getContributorPhotos(
          address
        );
        const donationDetails = await App.Foundationcontract.getDonationDetails(
          address
        );
        const votedRequests = requestIds.map((id, index) => ({
          uniqueid: id,
          recipient: requestAddresses[index],
          description: descriptions[index],
          targetMoney: targetAmounts[index],
          completed: completedStatus[index],
          photos: photos[index].split(","),
        }));
        setTotalDonation(totalDonationAmount);
        setAccountBalance(accountBalance);
        setVotedRequestData(votedRequests);
        setDonationDetails(donationDetails);
      } catch (error) {
        console.error("Error fetching user data:", error);
      }
      setLoading(false);
    };

    const fetchPersonalRequests = async () => {
      setLoading(true);
      try {
        const userRequestCount =
          await App.Foundationcontract.userrequestsNumber();
        let personalRequests = [];

        for (let i = 0; i < userRequestCount; i++) {
          const request = await App.Foundationcontract.userrequestions(i);
          if (request.creator.toLowerCase() === address.toLowerCase()) {
            personalRequests.push(request);
          }
        }

        setPersonalRequests(personalRequests);
      } catch (error) {
        console.error("Error fetching personal requests:", error);
      }
      setLoading(false);
    };
    fetchUserData();
    fetchPersonalRequests();
  }, [address, App.Foundationcontract]);

  const formatDate = (timestamp) => {
    const date = new Date(timestamp * 1000);
    return `${date.getFullYear()}年${
      date.getMonth() + 1
    }月${date.getDate()}日 ${date.getHours()}时${date.getMinutes()}分${date.getSeconds()}秒`;
  };

  useEffect(() => {
    const convertTimestampToDate = (timestamp) => {
      const date = new Date(timestamp * 1000);
      return date.toLocaleString();
    };
    const methodIdToFunctionName = {
      "0xcbedbf5a": "首页捐赠",
      "0x4cb6f4a5": "投票",
      "0x8483e4cf": "用户区域捐款",
      "0x33d6798d": "创建筹款",
      "0x6e417c69": "管理员拨款",
      "0x97fd8ec8": "管理员发起筹款",
    };
    const fetchTransactions = async () => {
      const apiKey = "3KB3FGVCMBA1TCY1P9KWHC61SEAZECGI3T";
      const network = "sepolia";
      const url = `https://api-${network}.etherscan.io/api?module=account&action=txlist&address=${address}&startblock=0&endblock=99999999&sort=asc&apikey=${apiKey}`;

      try {
        const contractAddress = App.Foundationcontract.address.toLowerCase();
        console.log(contractAddress);
        const response = await axios.get(url);
        console.log(response.data.result);
        if (response.data.status === "1") {
          const filteredTransactions = response.data.result.filter(
            (tx) => tx.to.toLowerCase() === contractAddress
          );
          console.log(filteredTransactions);
          const transactionsWithTypes = filteredTransactions.map((tx) => {
            let type = methodIdToFunctionName[tx.methodId] || "未知操作";

            return {
              ...tx,
              type,
              readableDate: convertTimestampToDate(tx.timeStamp),
            };
          });
          console.log(transactionsWithTypes);
          setTransactions(transactionsWithTypes);
        } else {
          console.error("Failed to fetch transactions:", response.data.message);
        }
      } catch (error) {
        console.error("Error fetching transactions:", error);
      }
    };
    fetchTransactions();
  }, [address]);

  const handleTransactionView = (hash) => {
    navigate(`/header/blockDetails?hash=${encodeURIComponent(hash)}`);
  };

  const renderContent = () => {
    switch (currentView) {
      case "personal-info":
        return (
          <div className="left-side">
            <h1 className="profile-title">个人信息</h1>
            <label className="label">
              <FaUser />
              地址
            </label>
            <input
              type="text"
              id="full-name"
              name="full-name"
              value={address}
              readOnly
              className="inputStyle"
              disabled
            />
            <label className="label">
              <FaDonate />
              总捐款金额(WEI)
            </label>
            <input
              type="text"
              id="total-donation"
              name="total-donation"
              value={totalDonation}
              readOnly
              className="inputStyle"
              disabled
            />
            <label className="label">
              <FaWallet />
              账户余额(WEI)
            </label>
            <input
              type="text"
              id="account-balance"
              name="account-balance"
              value={accountBalance}
              readOnly
              className="inputStyle"
              disabled
            />
          </div>
        );
      case "voted-records":
        const votedRecordsStartIndex =
          (currentPage.votedRecords - 1) * itemsPerPage;
        const votedRecordsToShow = votedRequestData.slice(
          votedRecordsStartIndex,
          votedRecordsStartIndex + itemsPerPage
        );
        return (
          <div className="right-side">
            <h1 className="profile-title">已投票的筹款请求信息</h1>
            {votedRecordsToShow.length === 0 ? (
              <p>暂无投票记录</p>
            ) : (
              votedRecordsToShow.map((request, index) => (
                <div key={index} className="vote-record">
                  <div className="vote-record-icon">
                    <FaCheck />
                  </div>
                  <div className="vote-record-content">
                    <p>投票地址：{request.recipient}</p>
                    <p>请求描述：{request.description}</p>
                    <p>目标金额：{request.targetMoney.toString()} WEI</p>
                    <p>状态：{request.completed ? "已完成" : "未完成"}</p>
                  </div>
                  <div className="right-content">
                    <Link
                      key={index}
                      to={`/header/songwarm/${request.uniqueid}`}
                      className="image-link"
                    >
                      <img
                        src={`https://blush-chemical-hedgehog-894.mypinata.cloud/ipfs/${request.photos[0]}`}
                        alt="首张照片"
                      />
                    </Link>
                  </div>
                </div>
              ))
            )}
            <Pagination
              currentPage={currentPage.votedRecords}
              totalPages={totalPages.votedRecords}
              onPageChange={(page) => handlePageChange("votedRecords", page)}
            />
          </div>
        );
      case "donation-records":
        const donationRecordsStartIndex =
          (currentPage.donationRecords - 1) * itemsPerPage;
        const donationRecordsToShow = donationDetails.slice(
          donationRecordsStartIndex,
          donationRecordsStartIndex + itemsPerPage
        );
        return (
          <div className="right-side">
            <h1 className="profile-title">已捐款金额和时间</h1>
            {donationRecordsToShow.length === 0 ? (
              <p>暂无捐款记录</p>
            ) : (
              donationRecordsToShow.map((donation, index) => (
                <div key={index} className="donation-record">
                  <div className="donation-record-icon">
                    <FaMoneyBill />
                  </div>
                  <div className="donation-record-content">
                    <p>捐款金额：{donation.amount.toString()} WEI</p>
                    <p>时间戳：{formatDate(donation.timestamp)}</p>
                  </div>
                </div>
              ))
            )}
            <Pagination
              currentPage={currentPage.donationRecords}
              totalPages={totalPages.donationRecords}
              onPageChange={(page) => handlePageChange("donationRecords", page)}
            />
          </div>
        );
      case "hashs-records":
        const hashsRecordsStartIndex =
          (currentPage.hashsRecords - 1) * itemsPerPage;
        const hashsRecordsToShow = transactions.slice(
          hashsRecordsStartIndex,
          hashsRecordsStartIndex + itemsPerPage
        );
        return (
          <div className="right-side">
            <h1 className="profile-title">查看区块链浏览器交易记录</h1>
            {hashsRecordsToShow.length === 0 ? (
              <p>暂无区块链浏览器交易记录</p>
            ) : (
              hashsRecordsToShow.map((tx, index) => (
                <div
                  key={index}
                  className="vote-record"
                  onClick={() => handleTransactionView(tx.hash)}
                >
                  <div className="vote-record-icon">
                    <FaCheck />
                  </div>
                  <div className="vote-record-content">
                    <p>交易hash：{tx.hash}</p>
                    <p>交易类型：{tx.type}</p>
                    <p>交易日期：{tx.readableDate}</p>
                    <p>交易金额：{tx.value}</p>
                  </div>
                </div>
              ))
            )}
            <Pagination
              currentPage={currentPage.hashsRecords}
              totalPages={totalPages.hashsRecords}
              onPageChange={(page) => handlePageChange("hashsRecords", page)}
            />
          </div>
        );
      case "personal-requests":
        const personalRequestsStartIndex =
          (currentPage.personalRequests - 1) * itemsPerPage;
        const personalRequestsToShow = personalRequests.slice(
          personalRequestsStartIndex,
          personalRequestsStartIndex + itemsPerPage
        );
        return (
          <div className="right-side">
            <h1 className="profile-title">个人筹款记录</h1>
            {personalRequestsToShow.length === 0 ? (
              <p>暂无个人筹款记录</p>
            ) : (
              personalRequestsToShow.map((request, index) => (
                <div key={index} className="create_record">
                  <div className="create_record_content">
                    <img
                      src={`https://blush-chemical-hedgehog-894.mypinata.cloud/ipfs/${request.photo}`}
                    />
                    <div className="content_right_two">
                      <p>标题：{request.tittle}</p>
                      <p>描述：{request.description}</p>
                      <p>目标金额：{request.targetMoney.toString()} WEI</p>
                      <p>已筹金额：{request.userraisedAmount.toString()} WEI</p>
                      <p>结束时间：{formatDate(request.endTime)}</p>
                      <p
                        className={
                          request.completed
                            ? "status-completed"
                            : "status-not-completed"
                        }
                      >
                        状态：{request.completed ? "已结束" : "未结束"}
                      </p>
                    </div>
                  </div>
                </div>
              ))
            )}
            <Pagination
              currentPage={currentPage.personalRequests}
              totalPages={totalPages.personalRequests}
              onPageChange={(page) =>
                handlePageChange("personalRequests", page)
              }
            />
          </div>
        );
      default:
        return null;
    }
  };

  return (
    <div className="profileDiv">
      {loading && <div className="loader"></div>}
      <div className="container">
        <nav className="sidebar">
          <ul>
            <li>
              <button onClick={() => setCurrentView("personal-info")}>
                个人信息
              </button>
            </li>
            <hr />
            <li>
              <button onClick={() => setCurrentView("voted-records")}>
                投票记录
              </button>
            </li>
            <hr />
            <li>
              <button onClick={() => setCurrentView("donation-records")}>
                捐款记录
              </button>
            </li>
            <hr />
            <li>
              <button onClick={() => setCurrentView("hashs-records")}>
                查看区块链浏览器交易记录
              </button>
            </li>
            <hr />
            <li>
              <button onClick={() => setCurrentView("personal-requests")}>
                个人筹款记录
              </button>
            </li>
          </ul>
        </nav>
        {renderContent()}
      </div>
    </div>
  );
}
